﻿using System;
using System.Collections.Generic;
using Shell.Build;

namespace Shell.Advanced
{
    public static class IShellAdvancedHelper
    {
        public static IEnumerable<object> Resolve(IShell shell, Type targetType)
        {
            var holder = GetIShellRegistrationHolder(shell);
            foreach (var bi in GetMatchedBuildIdentity(holder, targetType))
            {
                yield return shell.Resolve(bi.Name, bi.Type);
            }
        }

        internal static IEnumerable<BuildIdentity> GetMatchedBuildIdentity(IShellRegistrationHolder holder, Type targetType)
        {
            if (holder != null)
            {
                foreach (var r in holder.Registrations)
                {
                    if (r is BuildIdentity)
                    {
                        var bi = r as BuildIdentity;
                        if (bi.Type == targetType)
                        {
                            yield return bi;
                        }
                    }
                }
            }
        }

        internal static IShellRegistrationHolder GetIShellRegistrationHolder(IShell shell)
        {
            if (shell is DefaultShell)
            {
                var defaultShell = shell as DefaultShell;
                foreach (var e in defaultShell.Extensions)
                {
                    if (e is ShellRegistrationRecorderExtension)
                    {
                        var ext = e as ShellRegistrationRecorderExtension;
                        return ext.ShellRegistrationHolder;
                    }
                }
            }
            return null;
        }
    }
}
